package com.lh.project.common;

import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class DateUtil {
    public static String getDateRange(Date startDate, Date endDate) {
        // 将 java.util.Date 转换为 java.time.LocalDateTime
        LocalDateTime start = convertToLocalDateTime(startDate);
        LocalDateTime end = convertToLocalDateTime(endDate);

        // 计算时间间隔
        Duration duration = Duration.between(start, end);

        // 判断时间间隔
        if (duration.toDays() > 365) { // 超过1年
            return duration.toDays() / 365 + "年前";
        } else if (duration.toDays() > 30) { // 超过1个月
            return duration.toDays() / 30 + "个月前";
        } else if (duration.toDays() > 0) { // 超过1天
            return duration.toDays() + "天前";
        } else {
            // 计算分钟间隔
            long minutes = duration.toMinutes();
            long hour = 0;
            if(minutes/60 !=0){
                hour = minutes/60;
            }

            if(hour>0){
                return hour +"小时前";
            }
            else if (minutes > 0) {
                return minutes + "分钟前";
            } else {
                return "1分钟以内"; // 小于1分钟
            }
        }
    }

    // 将 java.util.Date 转换为 java.time.LocalDateTime
    public static LocalDateTime convertToLocalDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }
}